﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Liju.Common;
using Liju.Model;
using LiJu.Db;
using LiJu.Model.Model;
using LiJu.Product.View;

namespace LiJu.Product
{
    public partial class ProductDetailControl : UserControl
    {
        /// <summary>
        /// 表格默认字体
        /// </summary>
        private Font defaultFont = new Font("Microsoft YaHei", 9);
        /// <summary>
        /// 电批参数
        /// </summary>
        public List<DDKScrewParam> screwdriverParams;
        /// <summary>
        /// 螺丝型号
        /// </summary>
        public List<ScrewModel> screwModels;
        /// <summary>
        /// 套筒型号
        /// </summary>
        public List<SleeveModel> sleeveModels;

        /// <summary>
        /// 任务集合
        /// </summary>
        public readonly List<TaskModel> taskModels = new List<TaskModel>();


        /// <summary>
        /// 初始化任务集合
        /// </summary>
        public List<TaskModel> initTaskModels = new List<TaskModel>();
        /// <summary>
        /// 所有任务集合
        /// </summary>
        public List<TaskModel> allTaskModels = new List<TaskModel>();
        /// <summary>
        /// 所有产品图片集合
        /// </summary>
        public List<ProductImgModel> allProductImgModels = new List<ProductImgModel>();



        /// <summary>
        /// 产品
        /// </summary>
        public ProductModel Product = new ProductModel();
        /// <summary>
        /// 产品页面类型
        /// </summary>
        public ProductViewType ProductViewType = ProductViewType.ProductAdd;

        /// <summary>
        /// 编码器通信
        /// </summary>
        //private ModbusRTU EncoderModbusRTU = null;

        /// <summary>
        /// 导航事件
        /// </summary>
        public Action<ProductViewType> NavigateEvent;

        public ProductDetailControl()
        {
            InitializeComponent();
            InitGdview_Task();

            productImgControl1.AddTaskEvent += AddTaskEventFunc;
            productImgControl1.SelectTaskEvent += TaskSelectedFunc;
            productImgControl1.DeleteTaskEvent += DeleteTaskEventFunc;
            productImgControl1.RefreshTaskEvent += RefreshTaskFunc;

        }

        #region 方法

        /// <summary>
        /// 切换产品显示页
        /// </summary>
        public void ChangeProductView(ProductViewType type)
        {
            try
            {
                ProductViewType = type;
                if (type == ProductViewType.ProductAdd)
                {
                    //TableLayoutPanelHelper.SetTableLayoutRowHeight(tbLayoutPanel_TaskData, 1, 50);
                    gdview_Task.ReadOnly = false;
                    btn_Back.Visible = false;
                    btn_Cancel.Visible = true;
                    btn_Save.Visible = true;
                    panel_EditProduct1.Enabled = true;
                    panel_EditProduct2.Enabled = true;
                    productImgControl1.AllowDragFlag = true;
                    btn_GetScrewLocation.Enabled = true;
                    btn_AddWorkNum.Enabled = true;
                    productImgControl1.ProductWorkNum = 1;

                    RefreshWorkNum(productImgControl1.ProductWorkNum);
                    #region 20241029 zhanghl 已移到btn_AddTask_Click
                    //AddDefaultPoruduct();   
                    #endregion
                }
                else if (type == ProductViewType.ProductDetail)
                {
                    //TableLayoutPanelHelper.SetTableLayoutRowHeight(tbLayoutPanel_TaskData, 1, 0);
                    gdview_Task.ReadOnly = true;
                    btn_Back.Visible = true;
                    btn_Cancel.Visible = false;
                    btn_Save.Visible = false;
                    panel_EditProduct1.Enabled = false;
                    panel_EditProduct2.Enabled = false;
                    productImgControl1.AllowDragFlag = false;
                    btn_GetScrewLocation.Enabled = false;
                    btn_AddWorkNum.Enabled = false;
                    RefreshProducDetials();
                }
                else if (type == ProductViewType.ProductEdit)
                {
                    //TableLayoutPanelHelper.SetTableLayoutRowHeight(tbLayoutPanel_TaskData, 1, 0);
                    gdview_Task.ReadOnly = false;
                    btn_Back.Visible = false;
                    btn_Cancel.Visible = true;
                    btn_Save.Visible = true;
                    panel_EditProduct1.Enabled = true;
                    panel_EditProduct2.Enabled = true;
                    productImgControl1.AllowDragFlag = true;
                    btn_GetScrewLocation.Enabled = true;
                    btn_AddWorkNum.Enabled = true;
                    RefreshProducDetials();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，ChangeProductView->{ex.Message}");
            }

        }

        /// <summary>
        /// 初始化任务列表
        /// </summary>
        private void InitGdview_Task()
        {
            try
            {
                gdview_Task.RowsDefaultCellStyle.BackColor = Color.LightGreen;
                gdview_Task.AlternatingRowsDefaultCellStyle.BackColor = Color.White;
                // 设置选中单元格的背景颜色
                gdview_Task.DefaultCellStyle.SelectionBackColor = Color.Orange;
                // 设置选中单元格的前景颜色
                gdview_Task.DefaultCellStyle.SelectionForeColor = Color.Black;
                gdview_Task.RowTemplate.Height = 28;

                gdview_Task.MultiSelect = true;
                gdview_Task.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                gdview_Task.ClearSelection();
                gdview_Task.CurrentCell = null;
                gdview_Task.MouseUp += Gdview_Task_MouseUp;
                // 设置不允许修改行高
                gdview_Task.AllowUserToResizeRows = false;
                // 设置不允许修改列宽
                gdview_Task.AllowUserToResizeColumns = false;
                // 假设您的DataGridView控件名为dataGridView1
                gdview_Task.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                //显示行网格线，隐藏列网格线
                this.gdview_Task.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;
                this.gdview_Task.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
                this.gdview_Task.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;
                this.gdview_Task.DefaultCellStyle.Font = defaultFont;
                gdview_Task.CellBeginEdit += Gdview_Task_CellBeginEdit;
                gdview_Task.CellEndEdit += Gdview_Task_CellEndEdit;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，初始化任务列表->{ex.Message}");
            }

        }


        /// <summary>
        /// DataGridView鼠标点击弹起，行选中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Gdview_Task_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                if (gdview_Task.SelectedRows.Count > 0)
                {
                    var screwNums = gdview_Task.SelectedRows.Cast<DataGridViewRow>().Select(r => r.Index + 1).ToList();
                    //Dictionary<int,int> tasks=new Dictionary<int,int>();
                    List<WorkNumKeyValue> tasks = new List<WorkNumKeyValue>();
                    for (int i = 0; i < screwNums.Count; i++)
                    {
                        string workNumStr = gdview_Task.Rows[screwNums[i] - 1].Cells["WorkNum"].Value?.ToString().Trim();
                        string taskNumStr = gdview_Task.Rows[screwNums[i] - 1].Cells["TaskNum"].Value?.ToString().Trim();
                        if (int.TryParse(workNumStr, out int workNum) && int.TryParse(taskNumStr, out int taskNum))
                        {
                            tasks.Add(new WorkNumKeyValue() { WorkNum = workNum, Num = taskNum });
                        }
                    }
                    productImgControl1.SelectScrews(tasks);
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，Gdview_Task_MouseUp->{ex.Message}");
            }

        }

        /// <summary>
        /// 刷新任务
        /// </summary>
        private void RefreshTasks(List<TaskModel> taskModels)
        {
            try
            {
                gdview_Task.Rows.Clear();
                (gdview_Task.Columns["ScrewDriverParam"] as DataGridViewComboBoxColumn).DataSource = screwdriverParams;
                (gdview_Task.Columns["ScrewDriverParam"] as DataGridViewComboBoxColumn).DisplayMember = "name";

                (gdview_Task.Columns["SleeveModel"] as DataGridViewComboBoxColumn).DataSource = sleeveModels;
                (gdview_Task.Columns["SleeveModel"] as DataGridViewComboBoxColumn).DisplayMember = "Model";

                (gdview_Task.Columns["ScrewModel"] as DataGridViewComboBoxColumn).DataSource = screwModels;
                (gdview_Task.Columns["ScrewModel"] as DataGridViewComboBoxColumn).DisplayMember = "Model";
                for (int i = 0; i < taskModels.Count; i++)
                {
                    TaskModel task = taskModels[i];
                    gdview_Task.Rows.Add();
                    gdview_Task.Rows[i].Cells["WorkNum"].Value = task.WorkNum;
                    gdview_Task.Rows[i].Cells["TaskNum"].Value = task.Num;
                    gdview_Task.Rows[i].Cells["ProductImg"].Value = task.ProductImgNum;
                    gdview_Task.Rows[i].Cells["ScrewLocation"].Value = task.ScrewLocation;
                    gdview_Task.Rows[gdview_Task.RowCount - 1].Cells["ErrorLimit"].Value = task.ErrorLimit;
                    gdview_Task.Rows[gdview_Task.RowCount - 1].Cells["RadiusError"].Value = task.RadiusError;
                    DDKScrewParam screwdriverParam = screwdriverParams.Find(c => c.taskId == task.ScrewDriverParam);
                    if (screwdriverParam != null)
                    {
                        if (screwdriverParams.Exists(p => p.name == screwdriverParam.name))
                        {
                            gdview_Task.Rows[i].Cells["ScrewDriverParam"].Value = screwdriverParam.name;
                        }

                    }
                    SleeveModel sleevemodel = sleeveModels.Find(c => c.Id == task.SleeveModel);
                    if (sleevemodel != null)
                    {
                        if (sleeveModels.Exists(p => p.Model == sleevemodel.Model))
                        {
                            gdview_Task.Rows[i].Cells["SleeveModel"].Value = sleevemodel.Model;
                        }
                    }
                    ScrewModel screwmodel = screwModels.Find(c => c.Id == task.ScrewModel);
                    if (screwmodel != null)
                    {
                        if (screwModels.Exists(p => p.Model == screwmodel.Model))
                        {
                            gdview_Task.Rows[i].Cells["ScrewModel"].Value = screwmodel.Model;
                        }

                    }
                    gdview_Task.Rows[i].Cells["SkipTask"].Value = task.Skip == 0 ? false : true;
                    gdview_Task.Rows[i].Cells["TightenPrepare"].Value = task.TightenPrepare == 0 ? false : true;
                    gdview_Task.Rows[i].Selected = false;
                    gdview_Task.Rows[i].Cells["Id"].Value = task.Id;
                }
                productImgControl1.ClearAllSelectScrews();
                productImgControl1.ChangeProductImgIndex(1);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，刷新任务->{ex.Message}");
            }

        }
        /// <summary>
        /// 更新产品详情
        /// </summary>
        private void RefreshProducDetials()
        {
            try
            {
                if (!string.IsNullOrEmpty(Product.ProductName))
                {
                    txt_ProductName.Text = Product.ProductName;
                }
                if (!string.IsNullOrEmpty(Product.BarCode))
                {
                    txt_ProductIdentify.Text = Product.BarCode;
                }
                allProductImgModels = ProductImgDbHelper.GetAllProductImgByProductId(Product.Id);
                allTaskModels = TaskDbHelper.GetAllTaskByProductIdOrderNum(Product.Id);

                initTaskModels.Clear();
                initTaskModels.AddRange(allTaskModels);

                productImgControl1.ProductWorkNum = allTaskModels.Max(t => t.WorkNum);
                productImgControl1.CurrentProductWorkNum = 1;

                List<ProductImgModel> editProductImgModels = new List<ProductImgModel>();
                List<TaskModel> editTaskModels = new List<TaskModel>();
                editProductImgModels = allProductImgModels.FindAll(p => p.WorkNum == productImgControl1.CurrentProductWorkNum);
                editTaskModels = allTaskModels.FindAll(p => p.WorkNum == productImgControl1.CurrentProductWorkNum);
                //productImgControl1.InitProductImg(editProductImgModels, editTaskModels);

                productImgControl1.InitProductData(allProductImgModels, allTaskModels);
                productImgControl1.ChangeWorkNum(productImgControl1.CurrentProductWorkNum);

                RefreshTasks(editTaskModels);

                this.BeginInvoke(new Action(() =>
                {
                    RefreshWorkNum(productImgControl1.ProductWorkNum, false);
                    cbx_WorkNum.SelectedIndex = 0;
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，更新产品详情->{ex.Message}");
            }

        }

        /// <summary>
        /// 清除产品数据
        /// </summary>
        private void ClearProductData()
        {
            Product = new ProductModel();
            taskModels.Clear();
            productImgControl1.ClearData();
            gdview_Task.Rows.Clear();
            txt_ProductName.Text = null;
            txt_ProductIdentify.Text = null;
            allProductImgModels.Clear();
            allTaskModels.Clear();
            oldWorkNum = 1;

            addTaskFlag = false;
            productImgControl1.AddScrewFlag = false;
            btn_AddTask.Text = "添加任务";
        }

        /// <summary>
        /// 保存产品
        /// </summary>
        private void SaveProduct()
        {
            try
            {
                if (productImgControl1.ProductImg == null)
                {
                    MessageBox.Show("请先添加产品图");
                    return;
                }

                for (int i = 0; i < gdview_Task.Rows.Count; i++)
                {
                    string screwdriverParamValue = gdview_Task.Rows[i].Cells["ScrewDriverParam"].Value?.ToString();
                    if (screwdriverParamValue == null)
                    {
                        MessageBox.Show("请选择任务参数");
                        return;
                    }

                    string sleevemodelValue = gdview_Task.Rows[i].Cells["SleeveModel"].Value?.ToString();
                    if (sleevemodelValue == null)
                    {
                        MessageBox.Show("请选择套筒型号");
                        return;
                    }

                    string screwmodelValue = gdview_Task.Rows[i].Cells["ScrewModel"].Value?.ToString();
                    if (screwmodelValue == null)
                    {
                        MessageBox.Show("请选择螺丝型号");
                        return;
                    }
                }

                if (ProductViewType == ProductViewType.ProductEdit)
                {

                    StorageProductImgTasks(productImgControl1.CurrentProductWorkNum);

                    if (allTaskModels.Exists(p => p.ScrewDriverParam == 0))
                    {
                        MessageBox.Show("请选择任务参数");
                        return;
                    }
                    //if (allTaskModels.Exists(p => p.ScrewModel == 0))
                    //{
                    //    MessageBox.Show("请选择螺丝型号");
                    //    return;
                    //}
                    if (allTaskModels.Exists(p => p.SleeveModel == 0))
                    {
                        MessageBox.Show("请选择套筒型号");
                        return;
                    }

                    // 读取配置
                    string userName = ConfigurationManager.AppSettings["UserName"];
                    Product.ProductName = txt_ProductName.Text;
                    Product.BarCode = txt_ProductIdentify.Text;
                    Product.TaskNum = allTaskModels.Count;
                    Product.ImgNum = allProductImgModels.Count;
                    Product.CreateTime = DateTime.Now.ToString();
                    Product.Status = (int)ProductStatus.Enable;
                    Product.Creater = userName;
                    ProductDbHelper.UpdateProduct(Product);

                    ProductImgDbHelper.DeleteProductImgByProductId(Product.Id);
                    allProductImgModels = allProductImgModels.OrderBy(p => p.WorkNum).ToList();
                    foreach (var imgModel in allProductImgModels)
                    {
                        ProductImgDbHelper.AddProductImg(imgModel);
                    }

                    foreach (TaskModel task in initTaskModels)
                    {
                        if (allTaskModels.Exists(t => t.Id == task.Id && task.Id > 0))
                        {
                            TaskModel taskUpdate = allTaskModels.Find(t => t.Id == task.Id && task.Id > 0);
                            TaskDbHelper.UpdateProductTask(taskUpdate);
                        }
                        else
                        {
                            if (task.Id > 0)
                            {
                                TaskDbHelper.DeleteTaskByTaskId(task.Id);
                            }
                        }
                    }

                    foreach (TaskModel task in allTaskModels)
                    {
                        if (!initTaskModels.Exists(t => t.Id == task.Id))
                        {
                            TaskDbHelper.AddProductTask(task);
                        }
                    }


                }
                else
                {
                    StorageProductImgTasks(productImgControl1.CurrentProductWorkNum);

                    if (allTaskModels.Exists(p => p.ScrewDriverParam == 0))
                    {
                        MessageBox.Show("请选择任务参数");
                        return;
                    }
                    //if (allTaskModels.Exists(p => p.ScrewModel == 0))
                    //{
                    //    MessageBox.Show("请选择螺丝型号");
                    //    return;
                    //}
                    if (allTaskModels.Exists(p => p.SleeveModel == 0))
                    {
                        MessageBox.Show("请选择套筒型号");
                        return;
                    }

                    // 读取配置
                    string userName = ConfigurationManager.AppSettings["UserName"];
                    Product.ProductName = txt_ProductName.Text;
                    Product.BarCode = txt_ProductIdentify.Text;
                    Product.TaskNum = allTaskModels.Count;
                    Product.ImgNum = allProductImgModels.Count;
                    Product.CreateTime = DateTime.Now.ToString();
                    Product.Status = (int)ProductStatus.Enable;
                    Product.Creater = userName;
                    ProductDbHelper.AddProduct(Product);


                    allProductImgModels = allProductImgModels.OrderBy(p => p.WorkNum).ToList();
                    foreach (var imgModel in allProductImgModels)
                    {
                        ProductImgDbHelper.AddProductImg(imgModel);
                    }

                    allTaskModels = allTaskModels.OrderBy(p => p.WorkNum).ToList();
                    foreach (var taskModel in allTaskModels)
                    {
                        TaskDbHelper.AddProductTask(taskModel);
                    }
                    allProductImgModels.Clear();
                    allTaskModels.Clear();

                }

                ClearProductData();
                NavigateEvent?.Invoke(ProductViewType.ProductList);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，保存产品->{ex.Message}");
            }

        }

        /// <summary>
        /// 复制产品窗体数据返回
        /// </summary>
        /// <param name="productName"></param>
        /// <param name="productSN"></param>
        private void CopyProduct(string productName, string productSN)
        {
            try
            {
                Product.Id = ProductDbHelper.GetMaxProductId() + 1;

                StorageProductImgTasks(productImgControl1.CurrentProductWorkNum);

                Product.ProductName = productName;
                Product.BarCode = productSN;
                Product.TaskNum = allTaskModels.Count;
                Product.ImgNum = allProductImgModels.Count;
                Product.CreateTime = DateTime.Now.ToString();
                Product.Status = (int)ProductStatus.Enable;
                Product.Creater = ConfigurationManager.AppSettings["UserName"];
                ProductDbHelper.AddProduct(Product);

                allProductImgModels = allProductImgModels.OrderBy(p => p.WorkNum).ToList();
                foreach (var imgModel in allProductImgModels)
                {
                    imgModel.ProductId = Product.Id;
                    ProductImgDbHelper.AddProductImg(imgModel);
                }

                allTaskModels = allTaskModels.OrderBy(p => p.WorkNum).ToList();
                foreach (var taskModel in allTaskModels)
                {
                    taskModel.ProductId = Product.Id;
                    TaskDbHelper.AddProductTask(taskModel);
                }
                allProductImgModels.Clear();
                allTaskModels.Clear();

                ClearProductData();
                NavigateEvent?.Invoke(ProductViewType.ProductList);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，复制产品->{ex.Message}");
            }

        }

        #region 事件方法

        private string oldvalue = null;
        /// <summary>
        /// 表格修改前保存旧数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>RadiusError
        private void Gdview_Task_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            //误差列
            if (e.ColumnIndex == 5 || e.ColumnIndex == 6)
            {
                oldvalue = gdview_Task.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            }

        }

        /// <summary>
        /// 表格修改后验证数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Gdview_Task_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //误差列
            if (e.ColumnIndex == 5 || e.ColumnIndex == 6)
            {
                string newvalue = gdview_Task.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                if (!double.TryParse(newvalue, out double value))
                {
                    MessageBox.Show("请输入有效数");
                    gdview_Task.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = oldvalue;
                }
                else
                {
                    //二次确认提示 add by zxm
                    DialogResult dlgResult = MessageBox.Show("您是否确认修改？", "确认修改", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dlgResult == DialogResult.Yes)
                    {
                        //确定修改，保存新值
                        gdview_Task.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = newvalue.Trim();
                    }
                    else
                    {
                        //取消选择，则撤销修改
                        gdview_Task.CancelEdit();
                        gdview_Task.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = oldvalue;
                    }
                }
            }
            //判断第 7、8列
            if (e.ColumnIndex == 7 || e.ColumnIndex == 8)
            {
                string newvalue = gdview_Task.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                //给当前列之后的行都赋值newvalue
                for (int i = e.RowIndex; i < gdview_Task.Rows.Count; i++)
                {
                    gdview_Task.Rows[i].Cells[e.ColumnIndex].Value = newvalue;
                }
            }
        }

        /// <summary>
        /// 添加任务事件
        /// </summary>
        private void AddTaskEventFunc(TaskModel task)
        {
            (gdview_Task.Columns["ScrewDriverParam"] as DataGridViewComboBoxColumn).DataSource = screwdriverParams;
            (gdview_Task.Columns["ScrewDriverParam"] as DataGridViewComboBoxColumn).DisplayMember = "name";

            (gdview_Task.Columns["SleeveModel"] as DataGridViewComboBoxColumn).DataSource = sleeveModels;
            (gdview_Task.Columns["SleeveModel"] as DataGridViewComboBoxColumn).DisplayMember = "Model";

            (gdview_Task.Columns["ScrewModel"] as DataGridViewComboBoxColumn).DataSource = screwModels;
            (gdview_Task.Columns["ScrewModel"] as DataGridViewComboBoxColumn).DisplayMember = "Model";
            gdview_Task.Rows.Add();
            gdview_Task.Rows[gdview_Task.RowCount - 1].Cells["WorkNum"].Value = task.WorkNum;
            gdview_Task.Rows[gdview_Task.RowCount - 1].Cells["TaskNum"].Value = task.Num;
            gdview_Task.Rows[gdview_Task.RowCount - 1].Cells["ProductImg"].Value = task.ProductImgNum;
            gdview_Task.Rows[gdview_Task.RowCount - 1].Cells["ScrewLocation"].Value = task.ScrewLocation;
            gdview_Task.Rows[gdview_Task.RowCount - 1].Cells["ErrorLimit"].Value = 0.02;
            gdview_Task.Rows[gdview_Task.RowCount - 1].Cells["RadiusError"].Value = 20;
            gdview_Task.Rows[gdview_Task.RowCount - 1].Cells["SkipTask"].Value = task.Skip == 0 ? false : true;
            gdview_Task.Rows[gdview_Task.RowCount - 1].Cells["TightenPrepare"].Value = task.TightenPrepare == 0 ? false : true;
            if (screwModels != null & screwModels.Count > 0)
            {
                DataGridViewComboBoxCell screwCell = gdview_Task.Rows[gdview_Task.RowCount - 1].Cells["ScrewModel"] as DataGridViewComboBoxCell;
                screwCell.Value = screwModels[screwModels.Count - 1].Model;
            }
            taskModels.Add(task);
            if (gdview_Task.Rows.Count == 1)
            {
                gdview_Task.Rows[0].Selected = false;
            }

        }

        /// <summary>
        /// 删除任务事件
        /// </summary>
        private void DeleteTaskEventFunc(List<int> nums, int deleteImgNum)
        {
            taskModels.Clear();
            int index = 0;
            for (int i = 0; i < gdview_Task.Rows.Count; i++)
            {
                if (!nums.Contains(i + 1))
                {
                    index++;
                    TaskModel taskModel = new TaskModel();
                    taskModel.Num = index;

                    string worknumStr = gdview_Task.Rows[i].Cells["WorkNum"].Value?.ToString();
                    if (int.TryParse(worknumStr, out int wroknum))
                    {
                        taskModel.WorkNum = wroknum;
                    }

                    string imgNumStr = gdview_Task.Rows[i].Cells["ProductImg"].Value?.ToString();
                    int.TryParse(imgNumStr, out int imgNum);
                    if (deleteImgNum > 0 && imgNum >= deleteImgNum)
                    {
                        imgNum = imgNum - 1;
                    }
                    taskModel.ProductImgNum = imgNum;
                    taskModel.ScrewLocation = gdview_Task.Rows[i].Cells["ScrewLocation"].Value?.ToString();
                    string errorlimitStr = gdview_Task.Rows[i].Cells["ErrorLimit"].Value?.ToString();
                    if (!string.IsNullOrEmpty(errorlimitStr))
                    {
                        if (double.TryParse(errorlimitStr, out double errorlimit))
                        {
                            taskModel.ErrorLimit = errorlimit;
                        }
                    }

                    string radiusErrorStr = gdview_Task.Rows[i].Cells["RadiusError"].Value?.ToString();
                    if (!string.IsNullOrEmpty(radiusErrorStr))
                    {
                        if (double.TryParse(radiusErrorStr, out double errorlimit))
                        {
                            taskModel.RadiusError = errorlimit;
                        }
                    }


                    string screwdriverParamValue = gdview_Task.Rows[i].Cells["ScrewDriverParam"].Value?.ToString();
                    if (screwdriverParamValue != null)
                    {
                        DDKScrewParam screwdriverParam = screwdriverParams.Find(c => c.name == screwdriverParamValue);
                        taskModel.ScrewDriverParam = (int)screwdriverParam.taskId;
                    }

                    string sleevemodelValue = gdview_Task.Rows[i].Cells["SleeveModel"].Value?.ToString();
                    if (sleevemodelValue != null)
                    {
                        SleeveModel sleeveModel = sleeveModels.Find(c => c.Model == sleevemodelValue);
                        taskModel.SleeveModel = (int)sleeveModel.Id;
                    }

                    string screwmodelValue = gdview_Task.Rows[i].Cells["ScrewModel"].Value?.ToString();
                    if (screwmodelValue != null)
                    {
                        ScrewModel screwModel = screwModels.Find(c => c.Model == screwmodelValue);
                        if (screwModel != null)
                        {
                            taskModel.ScrewModel = (int)screwModel.Id;
                        }
                        else
                        {
                            taskModel.ScrewModel = 0;
                        }

                    }
                    string skipStr = gdview_Task.Rows[i].Cells["SkipTask"].Value?.ToString();
                    taskModel.Skip = skipStr == "False" ? 0 : 1;

                    string tightenPrepareStr = gdview_Task.Rows[i].Cells["TightenPrepare"].Value?.ToString();
                    int tightenPrepare = tightenPrepareStr == "False" ? 0 : 1;
                    taskModel.TightenPrepare = tightenPrepare;

                    int.TryParse(gdview_Task.Rows[i].Cells["Id"].Value?.ToString(), out int taskId);
                    taskModel.Id = taskId > 0 ? taskId : 0;
                    taskModels.Add(taskModel);

                }
            }
            RefreshTasks(taskModels);
        }

        /// <summary>
        /// 刷新任务
        /// </summary>
        /// <param name="nums"></param>
        private void RefreshTaskFunc(List<WorkNumKeyValue> nums)
        {
            if (nums.Count != gdview_Task.Rows.Count)
            {
                return;
            }
            taskModels.Clear();
            for (int i = 0; i < gdview_Task.Rows.Count; i++)
            {
                TaskModel taskModel = new TaskModel();
                taskModel.WorkNum = nums[i].WorkNum;
                taskModel.Num = nums[i].Num;

                string imgNumStr = gdview_Task.Rows[i].Cells["ProductImg"].Value?.ToString();
                int.TryParse(imgNumStr, out int imgNum);
                taskModel.ProductImgNum = imgNum;
                taskModel.ScrewLocation = gdview_Task.Rows[i].Cells["ScrewLocation"].Value?.ToString();
                string errorlimitStr = gdview_Task.Rows[i].Cells["ErrorLimit"].Value?.ToString();
                if (!string.IsNullOrEmpty(errorlimitStr))
                {
                    if (double.TryParse(errorlimitStr, out double errorlimit))
                    {
                        taskModel.ErrorLimit = errorlimit;
                    }
                }

                string radiusErrorStr = gdview_Task.Rows[i].Cells["RadiusError"].Value?.ToString();
                if (!string.IsNullOrEmpty(radiusErrorStr))
                {
                    if (double.TryParse(radiusErrorStr, out double errorlimit))
                    {
                        taskModel.RadiusError = errorlimit;
                    }
                }


                string screwdriverParamValue = gdview_Task.Rows[i].Cells["ScrewDriverParam"].Value?.ToString();
                if (screwdriverParamValue != null)
                {
                    DDKScrewParam screwdriverParam = screwdriverParams.Find(c => c.name == screwdriverParamValue);
                    taskModel.ScrewDriverParam = (int)screwdriverParam?.taskId;
                }

                string sleevemodelValue = gdview_Task.Rows[i].Cells["SleeveModel"].Value?.ToString();
                if (sleevemodelValue != null)
                {
                    SleeveModel sleeveModel = sleeveModels.Find(c => c.Model == sleevemodelValue);
                    taskModel.SleeveModel = (int)sleeveModel?.Id;
                }

                string screwmodelValue = gdview_Task.Rows[i].Cells["ScrewModel"].Value?.ToString();
                if (screwmodelValue != null)
                {
                    ScrewModel screwModel = screwModels.Find(c => c.Model == screwmodelValue);
                    if (screwModel != null)
                    {
                        taskModel.ScrewModel = (int)screwModel?.Id;
                    }
                    else
                    {
                        taskModel.ScrewModel = 0;
                    }

                }
                //taskModel.ScrewDriverParam = gdview_Task.Rows[i].Cells["ScrewDriverParam"].Value?.ToString();
                //taskModel.SleeveModel = gdview_Task.Rows[i].Cells["SleeveModel"].Value?.ToString();
                //taskModel.ScrewModel = gdview_Task.Rows[i].Cells["ScrewModel"].Value?.ToString();
                string skipStr = gdview_Task.Rows[i].Cells["SkipTask"].Value?.ToString();
                taskModel.Skip = skipStr == "False" ? 0 : 1;

                string tightenPrepareStr = gdview_Task.Rows[i].Cells["TightenPrepare"].Value?.ToString();
                int tightenPrepare = tightenPrepareStr == "False" ? 0 : 1;
                taskModel.TightenPrepare = tightenPrepare;

                int.TryParse(gdview_Task.Rows[i].Cells["Id"].Value?.ToString(), out int taskId);
                taskModel.Id = taskId > 0 ? taskId : 0;
                taskModels.Add(taskModel);
            }
            RefreshTasks(taskModels);
        }

        /// <summary>
        /// 选择表格对应任务行
        /// </summary>
        /// <param name="worknum"></param>
        /// <param name="index"></param>
        /// <param name="seleted"></param>
        private void SelectTaskRow(int worknum, int index, bool seleted)
        {
            string workNumStr = worknum.ToString();
            string taskNumStr = (index + 1).ToString();
            for (int i = 0; i < gdview_Task.Rows.Count; i++)
            {
                string workNumRow = gdview_Task.Rows[i].Cells["WorkNum"].Value?.ToString().Trim();
                string numRow = gdview_Task.Rows[i].Cells["TaskNum"].Value?.ToString().Trim();
                if (workNumStr == workNumRow && taskNumStr == numRow)
                {
                    gdview_Task.Rows[i].Selected = seleted;
                }
            }
        }


        /// <summary>
        /// 任务选择事件
        /// </summary>
        /// <param name="num"></param>
        private void TaskSelectedFunc(int worknum, int num, bool seleted)
        {
            if (num >= 0 && num < gdview_Task.Rows.Count)
            {
                SelectTaskRow(worknum, num, seleted);
                //if (seleted)
                //{
                //    gdview_Task.Rows[num].Selected = true;
                //    //gdview_Task.Rows[num].DefaultCellStyle.BackColor = Color.Violet;
                //}
                //else
                //{
                //    gdview_Task.Rows[num].Selected = false;
                //    //if (num % 2 == 0)
                //    //{
                //    //    gdview_Task.Rows[num].DefaultCellStyle.BackColor = Color.LightGreen;
                //    //}
                //    //else
                //    //{
                //    //    gdview_Task.Rows[num].DefaultCellStyle.BackColor = Color.White;
                //    //}
                //}
            }
        }

        /// <summary>
        /// 刷新产品序号
        /// </summary>
        /// <param name="worknum"></param>
        /// <param name="selected"></param>
        private void RefreshWorkNum(int worknum, bool selected = true)
        {
            cbx_WorkNum.Items.Clear();
            for (int i = 1; i <= worknum; i++)
            {
                cbx_WorkNum.Items.Add(i);
            }
            if (selected)
            {
                cbx_WorkNum.SelectedIndex = cbx_WorkNum.Items.Count - 1;
            }
        }

        /// <summary>
        /// 添加默认产品图
        /// </summary>
        private void AddDefaultPoruduct()
        {
            productImgControl1.ProductId = Product.Id;
            // 获取选中的文件路径
            string defaultFilePath = Directory.GetCurrentDirectory() + $"\\p0.png";
            string picFolder = Directory.GetCurrentDirectory() + $"\\Picture\\";
            if (!Directory.Exists(picFolder))
            {
                Directory.CreateDirectory(picFolder);
            }

            Image img = Image.FromFile(defaultFilePath);
            if (!ImageHelper.ExistSameImage(productImgControl1.ProductImgs, img))
            {
                string picName = "default.png";
                string picSavePath = Path.Combine(picFolder, picName);
                if (!File.Exists(picSavePath))
                {
                    File.Copy(defaultFilePath, picSavePath);
                }
                img.Tag = picName;
                productImgControl1.ProductImg = img;
            }
        }
        #endregion

        #endregion

        /// <summary>
        /// 添加产品图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AddProduct_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                // 设置对话框的属性
                openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);// "D:\\"; // 设置初始目录
                openFileDialog.Filter = "图片文件(*.jpg;*.jpeg;*.gif;*.bmp;*.png)|*.jpg;*.jpeg;*.gif;*.bmp;*.png"; // 设置文件过滤器
                openFileDialog.FilterIndex = 1;
                openFileDialog.RestoreDirectory = true;

                // 显示对话框
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    productImgControl1.ProductId = Product.Id;
                    // 获取选中的文件路径
                    string selectedFilePath = openFileDialog.FileName;
                    string picFolder = Directory.GetCurrentDirectory() + $"\\Picture\\";
                    if (!Directory.Exists(picFolder))
                    {
                        Directory.CreateDirectory(picFolder);
                    }

                    Image img = Image.FromFile(selectedFilePath);
                    if (!ImageHelper.ExistSameImage(productImgControl1.ProductImgs, img))
                    {
                        string picName = DateTime.Now.ToString("yyyyMMddHHmmss") + System.IO.Path.GetExtension(selectedFilePath);
                        string picSavePath = Path.Combine(picFolder, picName);
                        File.Copy(selectedFilePath, picSavePath);
                        img.Tag = picName;
                        productImgControl1.ProductImg = img;
                    }
                    else
                    {
                        MessageBox.Show("请勿添加重复图片");
                    }
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show($"产品，添加产品->{ex.Message}");
            }

        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DeleteScrew_Click(object sender, EventArgs e)
        {
            try
            {
                productImgControl1.DeleteSelectScrew();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，删除任务->{ex.Message}");
            }
        }

        /// <summary>
        /// 删除所有任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DeleteAllSrcew_Click(object sender, EventArgs e)
        {
            try
            {
                productImgControl1.DeleteAllScrew();
                gdview_Task.Rows.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，删除所有任务->{ex.Message}");
            }
        }

        bool addTaskFlag = false;
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AddTask_Click(object sender, EventArgs e)
        {
            #region 20241029 zhl 默认添加产品图
            //if(productImgControl1.ProductImg==null && addTaskFlag==false)
            //{
            //    MessageBox.Show("请先添加产品图");
            //    return;
            //}
            if (productImgControl1.ProductImg == null && addTaskFlag == false)
            {
                AddDefaultPoruduct();
            }
            #endregion
            addTaskFlag = !addTaskFlag;
            if (addTaskFlag)
            {
                productImgControl1.AddScrewFlag = true;
                btn_AddTask.Text = "结束添加";
            }
            else
            {
                productImgControl1.AddScrewFlag = false;
                btn_AddTask.Text = "添加任务";
            }

        }

        /// <summary>
        /// 删除产品图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DeletePicture_Click(object sender, EventArgs e)
        {
            try
            {
                productImgControl1.DeleteSelectProductImg();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，删除产品图->{ex.Message}");
            }

        }

        /// <summary>
        /// 删除所有产品图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DeleteAllPicture_Click(object sender, EventArgs e)
        {
            try
            {
                productImgControl1.DeleteAllProductImg();
                gdview_Task.Rows.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，删除所有产品图->{ex.Message}");
            }

        }

        /// <summary>
        /// 复制产品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_CopyProduct_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Product.ProductName))
            {
                MessageBox.Show("只能复制已保存的产品");
                return;
            }
            CopyProdcut copyProdcut = new CopyProdcut();
            copyProdcut.CopyProductAction += CopyProduct;
            copyProdcut.ShowDialog();

            //Task.Run(() =>
            //{
            //    ProductEvent.SetTaskStatusEvent?.Invoke(1, 1, TestStatus.ReadyStart);
            //    Thread.Sleep(1000);
            //    ProductEvent.SetTaskStatusEvent?.Invoke(1, 2, TestStatus.ReadyTest);
            //    Thread.Sleep(1000);
            //    ProductEvent.SetTaskStatusEvent?.Invoke(2, 1, TestStatus.Testing);
            //    Thread.Sleep(1000);
            //    ProductEvent.SetTaskStatusEvent?.Invoke(2, 2, TestStatus.NG);
            //    Thread.Sleep(1000);
            //    ProductEvent.SetTaskStatusEvent?.Invoke(3, 1, TestStatus.Pass);
            //    Thread.Sleep(1000);
            //    ProductEvent.SetTaskStatusEvent?.Invoke(3, 2, TestStatus.ReadyTest);

            //});

        }

        /// <summary>
        /// 旋转产品图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_RotateProduct_Click(object sender, EventArgs e)
        {
            try
            {
                productImgControl1.RotateProductImg();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"产品，旋转产品图->{ex.Message}");
            }

        }

        /// <summary>
        /// 获取电批位置信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_GetScrewLocation_Click(object sender, EventArgs e)
        {
            try
            {
                string location = $"{UnifiedObj.arrayPosition[0]},{UnifiedObj.arrayPosition[1]},{UnifiedObj.arrayPosition[2]},{UnifiedObj.arrayPosition[3]}";
                if (gdview_Task.CurrentCell != null)
                {
                    gdview_Task.Rows[gdview_Task.CurrentCell.RowIndex].Cells["ScrewLocation"].Value = location;
                    productImgControl1.UpdateScrewLocation(gdview_Task.CurrentCell.RowIndex + 1, location);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"GetScrewLocation->{ex.Message}");
            }

        }

        /// <summary>
        /// 取消操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("取消后数据不保存", "返回产品页", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                ClearProductData();
                NavigateEvent?.Invoke(ProductViewType.ProductList);
            }

        }

        /// <summary>
        /// 保存产品信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Save_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(txt_ProductName.Text) || string.IsNullOrEmpty(txt_ProductIdentify.Text))
                {
                    MessageBox.Show("请输入产品名称和条码");
                    return;
                }
                if (productImgControl1.TaskCount == 0)
                {
                    MessageBox.Show("请添加任务");
                    return;
                }
                var product = ProductDbHelper.GetProductByCode(txt_ProductIdentify.Text.Trim());
                if (product != null && ProductViewType == ProductViewType.ProductAdd)
                {
                    MessageBox.Show("产品已存在");
                    return;
                }
                SaveProduct();
            }
            catch (Exception ex)
            {

                MessageBox.Show($"保存产品：{ex.Message}");
            }

        }

        /// <summary>
        /// 返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Back_Click(object sender, EventArgs e)
        {
            ClearProductData();
            NavigateEvent?.Invoke(ProductViewType.ProductList);
        }
        /// <summary>
        /// 添加产品工序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_AddWorkNum_Click(object sender, EventArgs e)
        {
            oldWorkNum = productImgControl1.CurrentProductWorkNum;
            if (gdview_Task.Rows.Count > 0)
            {
                productImgControl1.ProductWorkNum++;
            }
            else
            {
                MessageBox.Show("请先添加上个工序任务", "添加产品工序", MessageBoxButtons.OK);
                return;
            }
            RefreshWorkNum(productImgControl1.ProductWorkNum);
        }

        /// <summary>
        /// 暂存产品图片和任务
        /// </summary>
        private void StorageProductImgTasks(int worknum)
        {
            if (oldWorkNum <= 0) return;
            if (allProductImgModels.Exists(t => t.WorkNum == worknum))
            {
                allProductImgModels.RemoveAll(t => t.WorkNum == worknum);
            }

            for (int i = 0; i < productImgControl1.ProductImgs.Count; i++)
            {
                Image image = productImgControl1.ProductImgs[i];

                ProductImgModel productImgModel = new ProductImgModel();
                productImgModel.ProductId = Product.Id;
                productImgModel.WorkNum = worknum;
                productImgModel.ImgIndex = i + 1;

                productImgModel.Path = image.Tag.ToString();
                allProductImgModels.Add(productImgModel);
            }

            if (allTaskModels.Exists(t => t.WorkNum == worknum))
            {
                allTaskModels.RemoveAll(t => t.WorkNum == worknum);
            }
            for (int i = 0; i < gdview_Task.Rows.Count; i++)
            {

                TaskModel taskModel = new TaskModel();

                string numStr = gdview_Task.Rows[i].Cells["TaskNum"].Value?.ToString();
                if (int.TryParse(numStr, out int num))
                {
                    taskModel.Num = num;
                }

                string worknumStr = gdview_Task.Rows[i].Cells["WorkNum"].Value?.ToString();
                if (int.TryParse(worknumStr, out int wroknum))
                {
                    taskModel.WorkNum = wroknum;
                }
                taskModel.ProductId = Product.Id;
                string imgNumStr = gdview_Task.Rows[i].Cells["ProductImg"].Value?.ToString();
                int.TryParse(imgNumStr, out int imgNum);
                taskModel.ProductImgNum = imgNum;
                ScrewControl screw = productImgControl1.ScrewControls.Find(c => c.WorkNum == taskModel.WorkNum && c.Num == taskModel.Num);
                if (screw != null)
                {
                    taskModel.ScrewControlLocation = $"{screw.ControlPositon.X}, {screw.ControlPositon.Y}";
                }

                taskModel.ScrewLocation = gdview_Task.Rows[i].Cells["ScrewLocation"].Value?.ToString();
                string errorlimitStr = gdview_Task.Rows[i].Cells["ErrorLimit"].Value?.ToString();
                if (!string.IsNullOrEmpty(errorlimitStr))
                {
                    if (double.TryParse(errorlimitStr, out double errorlimit))
                    {
                        taskModel.ErrorLimit = errorlimit;
                    }
                }

                string radiusErrorStr = gdview_Task.Rows[i].Cells["RadiusError"].Value?.ToString();
                if (!string.IsNullOrEmpty(radiusErrorStr))
                {
                    if (double.TryParse(radiusErrorStr, out double errorlimit))
                    {
                        taskModel.RadiusError = errorlimit;
                    }
                }
                string screwdriverParamValue = gdview_Task.Rows[i].Cells["ScrewDriverParam"].Value?.ToString();
                if (screwdriverParamValue != null)
                {
                    DDKScrewParam screwdriverParam = screwdriverParams.Find(c => c.name == screwdriverParamValue);
                    taskModel.ScrewDriverParam = (int)screwdriverParam?.taskId;
                }

                string sleevemodelValue = gdview_Task.Rows[i].Cells["SleeveModel"].Value?.ToString();
                if (sleevemodelValue != null)
                {
                    SleeveModel sleeveModel = sleeveModels.Find(c => c.Model == sleevemodelValue);
                    taskModel.SleeveModel = (int)sleeveModel?.Id;
                }

                string screwmodelValue = gdview_Task.Rows[i].Cells["ScrewModel"].Value?.ToString();
                if (screwmodelValue != null)
                {
                    ScrewModel screwModel = screwModels.Find(c => c.Model == screwmodelValue);
                    if (screwModel != null)
                    {
                        taskModel.ScrewModel = (int)screwModel.Id;
                    }
                    else
                    {
                        taskModel.ScrewModel = 0;
                    }
                }
                string skipStr = gdview_Task.Rows[i].Cells["SkipTask"].Value?.ToString();
                taskModel.Skip = skipStr == "False" ? 0 : 1;

                string tightenPrepareStr = gdview_Task.Rows[i].Cells["TightenPrepare"].Value?.ToString();
                int tightenPrepare = tightenPrepareStr == "False" ? 0 : 1;
                taskModel.TightenPrepare = tightenPrepare;

                if (int.TryParse(gdview_Task.Rows[i].Cells["Id"].Value?.ToString(), out int taskId))
                {
                    taskModel.Id = taskId > 0 ? taskId : 0;
                }
                allTaskModels.Add(taskModel);
            }

            allProductImgModels = allProductImgModels.OrderBy(p => p.WorkNum).ToList();
            allTaskModels = allTaskModels.OrderBy(p => p.WorkNum).ToList();
        }


        /// <summary>
        /// 切换产品工序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbx_WorkNum_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (int.TryParse(cbx_WorkNum.Text, out int worknum))
            {
                StorageProductImgTasks(oldWorkNum);
                if (worknum <= productImgControl1.ProductWorkNum)
                {
                    productImgControl1.CurrentProductWorkNum = worknum;

                }
                //productImgControl1.ChangeWorkNum(productImgControl1.CurrentProductWorkNum);
                List<ProductImgModel> productImgModels = allProductImgModels.FindAll(p => p.WorkNum == productImgControl1.CurrentProductWorkNum);
                List<TaskModel> taskModels = allTaskModels.FindAll(p => p.WorkNum == productImgControl1.CurrentProductWorkNum);
                productImgControl1.InitProductImg(productImgModels, taskModels, true);
                RefreshTasks(taskModels);
            }
        }
        private int oldWorkNum = 1;
        private void cbx_WorkNum_DropDown(object sender, EventArgs e)
        {
            if (int.TryParse(cbx_WorkNum.Text, out int worknum))
            {
                oldWorkNum = worknum;
                //if(!allTaskModels.Exists(t=>t.WorkNum == worknum))
                //{
                //    StorageProductImgTasks(oldWorkNum);
                //}

            }
        }

        /// <summary>
        /// 删除最后工序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_DeleteLastWorkNum_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认删除最后一个工序?", "删除工序", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
            {
                return;
            }
            int deleteWorkNum = productImgControl1.ProductWorkNum;
            if (deleteWorkNum == 1)
            {
                MessageBox.Show("至少保留一个工序");
                return;
            }

            if (cbx_WorkNum.Items.Contains(deleteWorkNum))
            {
                cbx_WorkNum.Items.Remove(deleteWorkNum);
                oldWorkNum = 0;
                productImgControl1.ProductWorkNum = productImgControl1.ProductWorkNum - 1;
                productImgControl1.CurrentProductWorkNum = productImgControl1.ProductWorkNum;
                allProductImgModels.RemoveAll(o => o.WorkNum == deleteWorkNum);
                allTaskModels.RemoveAll(o => o.WorkNum == deleteWorkNum);
                cbx_WorkNum.SelectedIndex = cbx_WorkNum.Items.Count - 1;
            }
        }
    }
}